<template>
  <div class="dispatch-operation-page">
    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryForm" inline>
        <el-form-item label="水库名称">
          <el-input
            v-model="queryForm.reservoirName"
            placeholder="请输入水库名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="调度类型">
          <el-select
            v-model="queryForm.type"
            placeholder="请选择调度类型"
            clearable
            style="width: 150px"
          >
            <el-option label="防洪调度" value="flood-control" />
            <el-option label="供水调度" value="water-supply" />
            <el-option label="发电调度" value="power-generation" />
            <el-option label="生态调度" value="ecological" />
            <el-option label="应急调度" value="emergency" />
          </el-select>
        </el-form-item>
        <el-form-item label="运行状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择运行状态"
            clearable
            style="width: 120px"
          >
            <el-option label="正常运行" value="normal" />
            <el-option label="调度中" value="dispatching" />
            <el-option label="维护中" value="maintenance" />
            <el-option label="停运" value="stopped" />
          </el-select>
        </el-form-item>
        <el-form-item label="调度日期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="operation-card" shadow="never">
      <el-button type="primary" @click="handleAdd">新增调度</el-button>
      <el-button
        type="danger"
        :disabled="!selectedRows.length"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
      <el-button type="success" @click="handleExport">导出数据</el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="调度编号" width="120" />
        <el-table-column prop="reservoirName" label="水库名称" width="150" />
        <el-table-column prop="type" label="调度类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" />
        <el-table-column prop="endTime" label="结束时间" />
        <el-table-column prop="waterLevel" label="水位(m)" width="100" />
        <el-table-column prop="flow" label="流量(m³/s)" width="120" />
        <el-table-column prop="operator" label="调度员" width="100" />
        <el-table-column prop="status" label="运行状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityTagType(row.priority)">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" icon="View" @click="handleView(row)">查看</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <DispatchOperationFormDialog
      v-model:visible="dialogVisible"
      :form-data="currentRow"
      :is-view="isView"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DispatchOperationFormDialog from './components/DispatchOperationFormDialog.vue'

// 查询表单
const queryForm = reactive({
  reservoirName: '',
  type: '',
  status: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const currentRow = ref(null)
const isView = ref(false)

// 获取类型标签样式
const getTypeTagType = (type: string) => {
  const typeMap = {
    'flood-control': 'danger',
    'water-supply': 'primary',
    'power-generation': 'warning',
    'ecological': 'success',
    'emergency': 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap = {
    'flood-control': '防洪调度',
    'water-supply': '供水调度',
    'power-generation': '发电调度',
    'ecological': '生态调度',
    'emergency': '应急调度'
  }
  return typeMap[type] || type
}

// 获取状态标签样式
const getStatusTagType = (status: string) => {
  const statusMap = {
    normal: 'success',
    dispatching: 'warning',
    maintenance: 'info',
    stopped: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    normal: '正常运行',
    dispatching: '调度中',
    maintenance: '维护中',
    stopped: '停运'
  }
  return statusMap[status] || status
}

// 获取优先级标签样式
const getPriorityTagType = (priority: string) => {
  const priorityMap = {
    high: 'danger',
    medium: 'warning',
    low: 'success'
  }
  return priorityMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const priorityMap = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return priorityMap[priority] || priority
}

// 模拟API - 获取调度运行列表
const fetchDispatchOperationList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const mockData = [
      {
        id: 1,
        code: 'DO2024001',
        reservoirName: '青山水库',
        type: 'flood-control',
        startTime: '2024-01-15 08:00:00',
        endTime: '2024-01-15 18:00:00',
        waterLevel: 125.5,
        flow: 85.2,
        operator: '张三',
        status: 'normal',
        priority: 'high',
        phone: '13800138001',
        purpose: '防洪调度，确保下游安全',
        plan: '根据降雨预报，提前泄洪',
        result: '成功降低水位2.5米',
        remark: '调度效果良好'
      },
      {
        id: 2,
        code: 'DO2024002',
        reservoirName: '白云水库',
        type: 'water-supply',
        startTime: '2024-02-10 06:00:00',
        endTime: '2024-02-10 20:00:00',
        waterLevel: 98.3,
        flow: 45.8,
        operator: '李四',
        status: 'dispatching',
        priority: 'medium',
        phone: '13800138002',
        purpose: '城市供水调度',
        plan: '保证城市用水需求',
        result: '供水量达到预期目标',
        remark: '调度进行中'
      }
    ]
    
    let list = [...mockData]
    if (list.length < 10) {
      const target = Math.floor(Math.random() * 41) + 10
      const templates = mockData
      const priorities = ['high', 'medium', 'low']
      const statuses = ['normal', 'dispatching']
      while (list.length < target) {
        const base: any = templates[list.length % templates.length]
        const idx = list.length + 1
        list.push({
          ...base,
          id: idx,
          code: `DO${new Date().getFullYear()}${String(idx).padStart(3, '0')}`,
          reservoirName: `${base.reservoirName}-${idx}`,
          priority: priorities[idx % priorities.length],
          status: statuses[idx % statuses.length],
          phone: '1380013' + String(802 + idx).padStart(3, '0')
        })
      }
    }
    tableData.value = list
    pagination.total = list.length
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 模拟API - 删除调度运行记录
const deleteDispatchOperation = async (ids: number[]) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    ElMessage.success('删除成功')
    fetchDispatchOperationList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 模拟API - 导出数据
const exportDispatchOperation = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 查询
const handleQuery = () => {
  pagination.currentPage = 1
  fetchDispatchOperationList()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    reservoirName: '',
    type: '',
    status: '',
    dateRange: []
  })
  handleQuery()
}

// 新增
const handleAdd = () => {
  currentRow.value = null
  isView.value = false
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  currentRow.value = { ...row }
  isView.value = false
  dialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  currentRow.value = { ...row }
  isView.value = true
  dialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除这条调度记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteDispatchOperation([row.id])
  })
}

// 批量删除
const handleBatchDelete = () => {
  const ids = selectedRows.value.map((row: any) => row.id)
  ElMessageBox.confirm(`确定要删除选中的 ${ids.length} 条调度记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteDispatchOperation(ids)
  })
}

// 导出
const handleExport = () => {
  exportDispatchOperation()
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchDispatchOperationList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchDispatchOperationList()
}

// 弹窗成功回调
const handleDialogSuccess = () => {
  fetchDispatchOperationList()
}

// 初始化
onMounted(() => {
  fetchDispatchOperationList()
})
</script>

<style scoped>
.dispatch-operation-page {
  padding: 20px;
}

.query-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>